var reg_username;
var password;
var timeoutObject;					
function init_input_field( selector, filedname ) {
	$(selector).val(filedname);
	$(selector).css("color", "grey" );
	$(selector).focusin( function() {
		if( $(selector).val() == filedname ) {
			$(selector).val("");
			$(selector).css("color", "black" );
		}
	});
	$(selector).focusout( function() {
		if( $(selector).val() == "" ) {
			$(selector).val(filedname);
			$(selector).css("color", "grey" );
		}
	});
}
				
var logging = false;
function login () {
	if( logging ) return;
	logging = true;
	var content = $('#loginv2-login-login').html();
	$('#loginv2-login-login').html('<img src="img/24.gif" width="32" style="margin-top: 40px;"/>');
	$.ziPOST(
		'login', 
		{
			'login-name': $("#login-name").val(), 
			'login-psw': $("#login-password").val()
		},	
		function (r) {
			if( r == 1 ) {
				logging = false;
				window.location.reload();
			}
			else {
				$('#loginv2-login-login').html(content);
				$('#loginv2-login-login').mouseout();
				$("#login-password").addClass("error");
				$('#loginv2-input-error').fadeIn( 500 );
				setTimeout( function() {
					$('#loginv2-input-error').fadeOut( 500 );
					$("#login-password").removeClass( "error" );
				}, 4000 );
				logging = false;							
			}
		})
}
						
function init_input_field_shadow( selector, selector_s, filedname ) {
	$(selector_s).val(filedname);
	$(selector_s).css("color", "grey" );
																																
	$(selector).focusin( function() {
		$(selector_s).css("color", "#aaaaaa");
	});
	$(selector).keydown( function(event) {
		if( $(selector).val().length == 0 && event.keyCode != 8 ) {
			$(selector_s).val("");
		}
	});
	$(selector).keyup( function(event) {
		if( $(selector).val().length == 0 ) {
			$(selector_s).val(filedname);
		}
	});
	$(selector).focusout( function() {
		if( $(selector).val().length == 0 ) {
			$(selector_s).val(filedname);
		} else {
			$(selector_s).val("");
		}
		$(selector_s).css("color", "grey");
	});
	$(selector_s).focusin( function() {
		$(selector).focus();
	});
	$(selector_s).click( function() {
		$(selector).focus();
	});
}
function resized() {
	var winH  = $(window).height();
	if( winH > 650 ) {
		$('#loginv2-main').offset({
			top: (winH - 600)/2 + 20
		});
	} else {
		$('#loginv2-main').offset({
			top: 20
		});
	}
}																															
$( function() {											
	init_input_field( "#login-name", "Username" );
	init_input_field( "#login-password", "Password" );
																																
	init_input_field_shadow( "#reg_fullname", "#reg_fullname_s", "Your Nick Name" );
	init_input_field_shadow( "#reg_email", "#reg_email_s","E-Mail" );
	init_input_field_shadow( "#reg_username", "#reg_username_s", "Username" );
	init_input_field_shadow( "#reg_password", "#reg_password_s", "Password" );
	init_input_field_shadow( "#reg_invite", "#reg_invite_s", "Inivte code" ); // for beta testing
																															
	$("#loginv2-login-login").click( login );
	$(".loginv2-input").keyup( function(event){					
		if(event.keyCode == 13) {
			login();
		}
	});
						
	$( "#dialog:ui-dialog" ).dialog( "destroy" );
	var reg_username = $( "#reg_username" ),
	reg_email        = $( "#reg_email" ),
	reg_password     = $( "#reg_password" ),
	reg_inivte       = $( "#reg_invite" ),
	reg_username_s   = $( "#reg_username_s" ),
	reg_email_s      = $( "#reg_email_s" ),
	reg_password_s   = $( "#reg_password_s" ),
	reg_inivte_s     = $( "#reg_inivte_s" ),
	allFields = $( [] ).add( reg_email ).add( reg_username ).add( reg_password )
	.add( reg_email_s ).add( reg_username_s ).add( reg_password_s ),
	tips = $( ".validateTips" );

	function updateTips( t ) {
		$( "#waiting-dialog" ).dialog( "close" );
		tips
		.text( t )
		.addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 2500 );
		}, 500 );
	}

	function checkLength( o, os, n, min, max ) {
		if ( o.val().length > max || min > o.val().length ) {
			os.addClass( "error" );
			updateTips( "Length of " + n + " must be between " +
				min + " and " + max + "." );
			return false;
		} else {
			return true;
		}
	}
																											
	function checkRegexp( o, os, regexp, n ) {
		if ( !( regexp.test( o.val() ) ) ) {
			os.addClass( "error" );
			updateTips( n );
			return false;
		} else {
			return true;
		}
	}
																													
	function checkEmail( o, os, callback ) {
		var reg = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		if (checkRegexp( o, os, reg, 'Invalid email address format' )) {
			$.ziGET(
				'checkfield', 
				{   
					'field':	 'email',
					'data':       o.val()
				},
				function(r) {
					if( r == 1 ) {
						os.addClass( "valid_s" );
						if( callback != undefined )
							callback();
						return true;
					} else {
						os.addClass( "error" );
						updateTips( "This email address has been used!" );
						return false;
					}
				});	
		} else {
			return false;
		}
	}
																										
	function checkUsername( o, os, callback ) {
		if (checkRegexp( o, os, 
			/^[a-z]([0-9a-z_])+$/i, 
			"Username may consist of a-z, 0-9, underscores, begin with a letter." )) {
			$.ziGET(
				'checkfield', 
				{   
					'field':	 'username',
					'data':       o.val()
				},
				function(r) {
					if( r == 1 ) {
						os.addClass( "valid_s" );
						if( callback != undefined )
							callback();
						return true;
					} else {
						os.addClass( "error" );
						updateTips( "This username has been used!" );
						return false;
					}
				});	
		} else {
			return false;
		}
	}
	function checkPassword( psw, os, callback ) {
		if( checkLength( psw, os, "password", 4, 16 ) ) {
			os.addClass( "valid_s" );
			if( callback != undefined )
				callback();
			return true;
		} else {
			return false;
		}
	}
	
	var agreement_expanded = false;
	$( "#register-form" ).dialog({
		autoOpen: false,
		width: 380,
		height: 360,
		show: 300,
		hide: 300,
		modal: true,
		resizable: false,
		buttons: {
			"Create Now": function() {
				var bValid = true;
				allFields.removeClass( "error" );
				$( "#waiting-dialog" ).dialog( "open" );
				bValid = bValid && 
				checkEmail( reg_email, reg_email_s,
					function () { 
						checkUsername( reg_username, reg_username_s,
							function () {
								checkPassword( reg_password, reg_password_s,
									function () {
										$.ziPOST(
											'register', 
											{
												'reg_username': reg_username.val(),
												'reg_password': reg_password.val(),
												'reg_email':    reg_email.val(),
												'reg_invite':   reg_inivte.val()
											},
											function(r) {
												$( "#waiting-dialog" ).dialog( "close" );
												switch( r ) {
													case 1:
														username = reg_username.val();
														password = reg_password.val();
														$( "#register-form" ).dialog( "close" );
														$( "#reg-succ-dialog" ).dialog( "open" );
														break;
													case 0:
														alert( 'Database error' );
														break;
													case -1:
														alert( 'either the email or the username is registered already.' );
														break;
													case -2:
														alert( 'Your invitation code is invalid.' );
														break;
												}
											});	
									})
							})
					});
			},
			Cancel: function() {
				$( this ).dialog( "close" );
				agreement_expanded = false;
				$('#register-form-agreements').css('overflow', 'hidden');
				$('#register-form-agreements').css('height', '30px');
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "error" );
			allFields.val( "" ).removeClass( "valid_s" );
		}
	});
	$( "#reg_username" ).change( function() {
		$("#reg_username_s").removeClass( "error" );
		$("#reg_username_s").removeClass( "valid_s" );
		checkUsername( $( "#reg_username" ), $("#reg_username_s") );
	});
	$( "#reg_email" ).change( function() {
		$("#reg_email_s").removeClass( "error" );
		$("#reg_email_s").removeClass( "valid_s" );
		checkEmail( $( "#reg_email" ), $("#reg_email_s")  );
	});
	$( "#reg_password" ).change( function() {
		$("#reg_password_s").removeClass( "error" );
		$("#reg_password_s").removeClass( "valid_s" );
		checkPassword( $( "#reg_password" ), $( "#reg_password_s" ) );
	});
																			
	$( "#reg-succ-dialog" ).dialog({
		autoOpen: false,
		width: 380,
		modal: true,
		show: "slide",
		hide: "opacity",
		resizable: false,
		buttons: {
			"Login now!": function() {
				$.ziPOST(
					'login', 
					{
						'login-name': username, 
						'login-psw': password
					},	
					function (r) {
						if(r==1)
							window.location.reload();
						else
							alert("Something is wrong");
					}
					)
			},
			Cancel: function() {
				$( 'input' ).trigger( "focusout" );
				$( this ).dialog( "close" );
													
			}
		}
	});	
										
	$( "#waiting-dialog" ).dialog({
		autoOpen: false,
		width: 400,
		height: 170,
		modal: true,
		show: "opacity",
		hide: "opacity",
		resizable: false
	});									
	$( "#loginv2-login-register" )
	.click(function() {
		$( 'input' ).trigger( "focusout" );
		$( "#register-form" ).dialog( "option", "position", 'center' );
		$( "#register-form" ).dialog( "open" );
	});
	$('#loginv2-login-forget').click( function(){
		alert("Not implemented yet!");
	} );	
	$('.reg_gender').click( function() {
		$('.reg_gender').attr( 'current', 'false' );
		$(this).attr('current', 'true');
	});
										
	$('#register-form-agreements').click( function() {
		if( agreement_expanded ) return;
		$('#register-form-agreements').css('overflow-y', 'auto');
		$('#register-form-agreements').animate( {
			height: 250
		} , 600 );	
		$('#register-form').animate( {
			height: 480
		} , 600, function() {
			$( "#register-form" ).dialog( "option", "position", 'center' );
		} );
											
		agreement_expanded = true;
	});
															
	//end of registration dialog window setup
	//.......................................
	$('#loginv2-login-container').css( 'height', 125 );
										
	// setup the news section animation
	var dur, centerNewsID = 0, maxid = 2;
	var newslock = false;
	$('.loginv2-news-arrow').click( function() {
		if(timeoutObject!=undefined){
			clearTimeout(timeoutObject);
			timeoutObject = setTimeout(function(){
				$('div[isLeft=false]').click();
			}, 20000);
		}
		if( newslock ) {
			return;
		} else {
			newslock = true;
		}
		dur = 500;
		if( $(this).attr('isleft') == 'true' ) {
			if( centerNewsID == 0 ) {
				centerNewsID = maxid;
				dur = 800;
			} else {
				centerNewsID --;
			}
		} else {
			if( centerNewsID == maxid ) {
				centerNewsID = 0;
				dur = 800;
			} else {
				centerNewsID ++;
			}
		}
		$('#loginv2-news-container').animate(
		{
			left: -$('#loginv2-news-page0').width()*centerNewsID
		}
		, { 
			duration: dur,
			queue: false,
			complete: function() {
				newslock = false;
			}
		} );
	});
	timeoutObject = setTimeout(function(){
		$('div[isLeft=false]').click();
	}, 20000);		
	
	//reposition elements when resize					
	$(window).resize(function(){
		resized();
	});
	resized();										
	// login buttons mouseover animations
	$('.login-button').hover( function(){
		$(this).find('.loginv2-login-button-text-capital').animate( {
			opacity: 0
		}, { 
			duration: 200,
			queue: false
		});
		$(this).find('.loginv2-login-button-text-normal').animate( {
			fontSize: 17,
			marginTop: -45
		}, { 
			duration: 200,
			queue: false
		} );
	}, function(){
		$(this).find('.loginv2-login-button-text-capital').animate( {
			opacity: 1
		} , 200 );
		$(this).find('.loginv2-login-button-text-normal').animate( {
			fontSize: 15,
			marginTop: 0
		} , 200 );
	});
});